package n143;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Stack;

/**
 * @author 苏文广
 * @since 2021/9/23
 */
public class Solution {

    public static void main(String[] args) {
        // 构造链表
        ListNode head = genNext();
        reorderList(head);
        System.out.println(head);
    }


    public static ListNode genNext() {
        ListNode head = null;
        head = new ListNode(1);
        genNext(head, 1, 4);
        return head;
    }

    private static void genNext(ListNode currNode, int curr, int max) {
        if (curr >= max) {
            return;
        }
        int val = curr + 1;
        ListNode next = new ListNode(val);
        currNode.next = next;
        genNext(next, val, max);
    }

    public static void reorderList(ListNode head) {
        ListNode temp = head;
        int num = 0;
        while (temp != null) {
            num++;
            temp = temp.next;
        }

        // 计算 左栈 结束节点
        int leftEnd = num / 2 + (num % 2);
        // 计算 右栈 开始节点
        int rightStart = num / 2 + 1;
        Queue<ListNode> left = new ArrayDeque<>();
        Stack<ListNode> right = new Stack<>();

        int i = 1;
        temp = head;
        while (temp != null) {
            if (i >= 1 && i <= leftEnd) {
                left.offer(temp);
            }

            if (i >= rightStart && i <= num) {
                right.push(temp);
            }

            temp = temp.next;
            i++;
        }


        temp = null;
        while (!left.isEmpty() && !right.isEmpty()) {
            ListNode poll = left.poll();
            ListNode pop = right.pop();

            if (temp == null) {
                temp = poll;
                temp.next = pop;
                temp = temp.next;
            } else if (!left.isEmpty()) {
                poll.next = pop;
                temp.next = poll;
                temp = pop;
            } else {
                if (pop == poll) {
                    temp.next = poll;
                    temp = temp.next;
                    temp.next = null;
                } else {
                    poll.next = pop;
                    temp.next = poll;
                    temp = pop;
                    pop.next = null;
                }
            }
        }
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}



